package thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 张杰
 * Date: 2022-04-13
 * Time: 19:17
 */
class MyThreadPool {
    //1.描述一个任务,直接使用Runnable,不需要额外创建类
    //2.使用一个数据结构来组织若干个任务(用来存储用户任务)
    private BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();


    //3.工作线程类,工作线程的功能就是从任务队列中取任务并执行(类 对其进行实例化)
    static class Worker extends Thread {
        //当前线程池中有若干个Worker线程,线程内部持有任务队列
        private BlockingQueue<Runnable> queue = null;
        public Worker(BlockingQueue<Runnable> queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            //需要能够拿到上面的队列
            while(true) {
                try {
                    //循环的去获取任务队列中的任务
                    //这里如果队列为空,就直接阻塞,如果队列非空,就获取到里面的内容
                    Runnable runnable = queue.take();
                    runnable.run();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    //4.创建一个数据结构来组织若干个工作线程.
    private List<Thread> workers = new ArrayList<>();//对工作线程进行实例化
    //线程池的构造方法
    public MyThreadPool(int n) {
        //在构造方法中,创建出若干个线程,放到上述的数组中
        for (int i = 0; i < n; i++) {
            Worker worker = new Worker(queue);
            worker.start();
            workers.add(worker);
        }
    }
    //5.创建一个方法,能够允许来放任务到线程池中
    public void submit(Runnable runnable) {
        try {
            queue.put(runnable);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
public class Demo17 {
    public static void main(String[] args) {
        MyThreadPool pool = new MyThreadPool(10);
        for (int i = 0; i < 100; i++) {
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("hello threadpool");
                }
            });
        }
    }
}
